package com.cah.game;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.cah.library.DatabaseHelper;
import com.cah.library.UserFunctions;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AccountsException;
import android.accounts.AuthenticatorException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class LoginActivity extends Activity
{
	Button loginButton;
	Spinner accountSpinner;
	AccountManager accountManager;
	Account[] accounts;
	HashMap<String, Account> usernameAccountMap;
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		loginButton = (Button)findViewById(R.id.login);
		accountSpinner = (Spinner)findViewById(R.id.account_spinner);
		
		ArrayList<String> gUsernameList = new ArrayList<String>();
	    accountManager = AccountManager.get(getApplicationContext());
		accounts = accountManager.getAccountsByType("com.google");
		usernameAccountMap = new HashMap<String, Account>();
		
		gUsernameList.clear();
		//loop
		for (Account account : accounts) {
		    gUsernameList.add(account.name);
		    usernameAccountMap.put(account.name, account);
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, gUsernameList);
		accountSpinner.setAdapter(adapter);
		
		loginButton.setOnClickListener(new View.OnClickListener()
		{		
			@Override
			public void onClick(View view)
			{
				String username = (String)accountSpinner.getSelectedItem();
				new LoginProcess().execute(username);
				
			}
		});
		
	}
	
	private String getAuthToken(Account account) throws AccountsException, IOException
	{
		AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, "ah", null, false, null, null);
		Bundle bundle = future.getResult();
	    Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
	    if (intent != null) {
	        startActivity(intent);
	    }
	    
	    return bundle.getString(AccountManager.KEY_AUTHTOKEN);
	}
	
	private class LoginProcess extends AsyncTask<String, Void, JSONObject>
	{
		String authToken, username;
		@Override
		protected JSONObject doInBackground(String... params)
		{
			username = params[0];
			Account account = usernameAccountMap.get(username);
			try
			{
				authToken = getAuthToken(account);
				UserFunctions uf = new UserFunctions();
				JSONObject json = uf.createUserOrLogin(authToken);
				return json;
			} catch (AuthenticatorException e)
			{
				e.printStackTrace();
			} catch (AccountsException e)
			{
				e.printStackTrace();
			}catch (IOException e)
			{
				e.printStackTrace();
			} 
			return null;
		}
		
		protected void onPostExecute(JSONObject json)
		{
			if(json == null)
			{
				accountManager.invalidateAuthToken("com.google", authToken);
				new LoginProcess().execute(username);
			}
			else
			{
				try
				{
					if(json.getInt(UserFunctions.KEY_SUCCESS)==1)
					{
						String userKey = json.getString(UserFunctions.KEY_VALUE);
						new SaveUserKeyProcess().execute(userKey);
						Intent lobbyIntent = new Intent(getApplicationContext(), MainActivity.class);
						lobbyIntent.putExtra("userKey", userKey);
						startActivity(lobbyIntent);
						finish();
					}
					else
					{
						Toast.makeText(getApplicationContext(), "Bad Username or Password", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}
		
	}
	
	private class SaveUserKeyProcess extends AsyncTask<String, Void, Void>
	{

		@Override
		protected Void doInBackground(String... arg0)
		{
			String userKey = arg0[0];
			DatabaseHelper dbhelper = new DatabaseHelper(getApplicationContext());
			dbhelper.setUserKey(userKey);
			return null;
		}
		
	}
}


